package com.youshang.protobuf.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import com.youshang.protobuf.common.Message.MessageBase;

/**
 *
 * @author youshang
 * @date 2021/08/12 21:55
 **/
public class PbServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        /*pipeline.addLast("my-server-ProtobufVarint32FrameDecoder",new ProtobufVarint32FrameDecoder()); //当前必须为第一个
        pipeline.addLast("my-server-ProtobufDecoder",new ProtobufDecoder(MyStudent.Student.getDefaultInstance())); //必须先解密
        pipeline.addLast("my-server-ProtobufEncoder",new ProtobufEncoder());
        pipeline.addLast("my-server-ProtobufVarint32LengthFieldPrepender",new ProtobufVarint32LengthFieldPrepender());*/

        //解码器必须放在前面，否则发数据收不到
        pipeline.addLast(new ProtobufVarint32FrameDecoder());//添加protobuff解码器
        pipeline.addLast(new ProtobufDecoder(MessageBase.getDefaultInstance()));//添加protobuff对应类解码器
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());//protobuf的编码器 和上面对对应
        pipeline.addLast(new ProtobufEncoder());//protobuf的编码器

        pipeline.addLast("my_server_PbServerHandle",new PbServerHandle());
    }
}
